package com.sh.data.engine.domain.integration.job;

import com.sh.data.engine.common.enumDefinition.OfflineSyncTaskStatus;
import com.sh.data.engine.domain.integration.offline.model.domain.OfflineSyncDomain;
import com.sh.data.engine.domain.integration.offline.model.domain.OfflineSyncDomain.OfflineSyncSchedule;
import com.sh.data.engine.domain.integration.offline.model.enums.OfflineSyncExecuTypeEnum;
import com.sh.data.engine.domain.integration.offline.service.DataXService;
import com.sh.data.engine.domain.integration.offline.service.OfflineSyncService;
import com.sh.data.engine.domain.integration.offline.service.impl.OfflineSyncRunningRecordServiceImpl;
import com.sh.data.engine.job.core.context.XxlJobHelper;
import com.sh.data.engine.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
public class OfflineSyncTask {

    // 离线同步id

    @Autowired
    private DataXService dataXService;

    @Autowired
    private OfflineSyncService offlineSyncService;

    @Autowired
    private OfflineSyncRunningRecordServiceImpl offlineSyncRunningRecordService;

    @XxlJob(value = "OfflineSyncHandler")
    public void run() {
        final long jobId = XxlJobHelper.getJobId();

        OfflineSyncDomain offlineSyncDomain =
            offlineSyncService.getOfflineSyncByXxlId(jobId);

        if (null == offlineSyncDomain) {
            XxlJobHelper.log("xxl-job id:{}对应的虎符中的任务不存在，执行结束....", jobId);
            return;
        }

        // 判断任务是否发布/是否上一个周期运行完成
        if (!offlineSyncDomain.getTaskStatus().equals(OfflineSyncTaskStatus.released.getTaskStatus())) {
            return;
        }

        boolean flag = false;
        OfflineSyncSchedule schedule = offlineSyncDomain.getSchedule();
        if (schedule != null && Objects.equals(schedule.getCycleDependence(), 1)) {
            flag = true;
        }

        Integer offlineSyncLastType =
            offlineSyncRunningRecordService.getOfflineSyncLastType(offlineSyncDomain.getId());
        if (flag
            && null != offlineSyncLastType
            && offlineSyncLastType.equals(OfflineSyncTaskStatus.running.getTaskStatus())) {
            return;
        }
        XxlJobHelper.log("任务拉起，开始异步执行");

        dataXService.executeOfflineSync(
            offlineSyncDomain.getId(), OfflineSyncExecuTypeEnum.AUTOMIC.getStatus());
    }
}
